"""
权限管理模块
"""

import json
import time
from typing import List, Dict, Any, Optional
from .auth_manager import AuthManager

class PermissionManager:
    """权限管理器"""
    
    def __init__(self, storage_manager, auth_manager: AuthManager):
        """初始化权限管理器"""
        self.storage_manager = storage_manager
        self.auth_manager = auth_manager
        
        # 权限类型定义
        self.PERMISSION_TYPES = {
            'SELECT': '查询',
            'INSERT': '插入',
            'UPDATE': '更新',
            'DELETE': '删除',
            'CREATE': '创建表',
            'DROP': '删除表',
            'ALTER': '修改表结构',
            'GRANT': '授权',
            'REVOKE': '撤销权限'
        }
    
    def check_permission(self, user_id: int, table_name: str, operation: str) -> bool:
        """检查用户是否有指定表的指定操作权限"""
        try:
            # 管理员拥有所有权限
            user = self._get_user_by_id(user_id)
            if user and user['role'] == 'admin':
                return True
            
            # 检查表是否存在
            if not self.storage_manager.table_exists(table_name):
                return False
            
            # 检查是否为表所有者
            if self._is_table_owner(user_id, table_name):
                return True
            
            # 检查显式权限
            permissions = self.storage_manager.query_table(
                'table_permissions',
                {
                    'table_name': table_name,
                    'user_id': user_id,
                    'permission_type': operation
                }
            )
            
            return len(permissions) > 0
            
        except Exception as e:
            print(f"权限检查错误: {e}")
            return False
    
    def grant_permission(self, user_id: int, table_name: str, permission_type: str, granted_by: int) -> bool:
        """授予权限"""
        try:
            # 检查授权者是否有GRANT权限
            if not self.check_permission(granted_by, table_name, 'GRANT'):
                return False
            
            # 检查权限类型是否有效
            if permission_type not in self.PERMISSION_TYPES:
                return False
            
            # 检查是否已存在相同权限
            existing = self.storage_manager.query_table(
                'table_permissions',
                {
                    'table_name': table_name,
                    'user_id': user_id,
                    'permission_type': permission_type
                }
            )
            
            if existing:
                return True  # 权限已存在
            
            # 创建权限记录
            permission_record = {
                'table_name': table_name,
                'user_id': user_id,
                'permission_type': permission_type,
                'granted_by': granted_by,
                'granted_at': str(int(time.time()))
            }
            
            self.storage_manager.insert_record('table_permissions', permission_record)
            return True
            
        except Exception as e:
            print(f"授权错误: {e}")
            return False
    
    def revoke_permission(self, user_id: int, table_name: str, permission_type: str, revoked_by: int) -> bool:
        """撤销权限"""
        try:
            # 检查撤销者是否有GRANT权限
            if not self.check_permission(revoked_by, table_name, 'GRANT'):
                return False
            
            # 删除权限记录
            self.storage_manager.delete_record(
                'table_permissions',
                {
                    'table_name': table_name,
                    'user_id': user_id,
                    'permission_type': permission_type
                }
            )
            return True
            
        except Exception as e:
            print(f"撤销权限错误: {e}")
            return False
    
    def get_user_permissions(self, user_id: int) -> List[Dict[str, Any]]:
        """获取用户的所有权限"""
        try:
            permissions = self.storage_manager.query_table(
                'table_permissions',
                {'user_id': user_id}
            )
            
            # 添加权限描述
            for perm in permissions:
                perm['description'] = self.PERMISSION_TYPES.get(perm['permission_type'], '未知权限')
            
            return permissions
            
        except Exception as e:
            print(f"获取用户权限错误: {e}")
            return []
    
    def get_table_permissions(self, table_name: str) -> List[Dict[str, Any]]:
        """获取表的所有权限"""
        try:
            permissions = self.storage_manager.query_table(
                'table_permissions',
                {'table_name': table_name}
            )
            
            # 添加用户信息
            for perm in permissions:
                user = self._get_user_by_id(perm['user_id'])
                perm['username'] = user['username'] if user else '未知用户'
                perm['description'] = self.PERMISSION_TYPES.get(perm['permission_type'], '未知权限')
            
            return permissions
            
        except Exception as e:
            print(f"获取表权限错误: {e}")
            return []
    
    def _is_table_owner(self, user_id: int, table_name: str) -> bool:
        """检查用户是否为表的所有者"""
        try:
            catalog_records = self.storage_manager.query_table(
                'system_catalog',
                {'table_name': table_name}
            )
            
            if catalog_records:
                return catalog_records[0]['owner_id'] == user_id
            
            return False
            
        except:
            return False
    
    def _get_user_by_id(self, user_id: int) -> Optional[Dict[str, Any]]:
        """根据用户ID获取用户信息"""
        try:
            users = self.storage_manager.query_table(
                'system_users',
                {'user_id': user_id}
            )
            return users[0] if users else None
        except:
            return None
    
    def set_table_owner(self, table_name: str, owner_id: int) -> bool:
        """设置表的所有者"""
        try:
            # 检查表是否已存在记录
            existing = self.storage_manager.query_table(
                'system_catalog',
                {'table_name': table_name}
            )
            
            if existing:
                # 更新所有者
                self.storage_manager.update_record(
                    'system_catalog',
                    {'table_name': table_name},
                    {'owner_id': owner_id}
                )
            else:
                # 创建新记录
                import time
                catalog_record = {
                    'table_name': table_name,
                    'owner_id': owner_id,
                    'created_at': str(int(time.time())),
                    'permissions': '{}'
                }
                self.storage_manager.insert_record('system_catalog', catalog_record)
            
            return True
            
        except Exception as e:
            print(f"设置表所有者错误: {e}")
            return False
    
    def grant_table_ownership(self, table_name: str, new_owner_id: int, granted_by: int) -> bool:
        """转移表所有权"""
        try:
            # 检查授权者是否有GRANT权限
            if not self.check_permission(granted_by, table_name, 'GRANT'):
                return False
            
            # 设置新所有者
            if self.set_table_owner(table_name, new_owner_id):
                # 授予新所有者所有权限
                for perm_type in ['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'ALTER', 'DROP', 'GRANT']:
                    self.grant_permission(new_owner_id, table_name, perm_type, granted_by)
                
                return True
            
            return False
            
        except Exception as e:
            print(f"转移表所有权错误: {e}")
            return False
    
    def get_permission_summary(self) -> Dict[str, Any]:
        """获取权限摘要信息"""
        try:
            # 统计各权限类型的数量
            all_permissions = self.storage_manager.query_table('table_permissions', {})
            
            permission_counts = {}
            for perm in all_permissions:
                perm_type = perm['permission_type']
                permission_counts[perm_type] = permission_counts.get(perm_type, 0) + 1
            
            # 统计用户权限数量
            user_permissions = {}
            for perm in all_permissions:
                user_id = perm['user_id']
                user_permissions[user_id] = user_permissions.get(user_id, 0) + 1
            
            return {
                'total_permissions': len(all_permissions),
                'permission_type_counts': permission_counts,
                'user_permission_counts': user_permissions,
                'permission_types': self.PERMISSION_TYPES
            }
            
        except Exception as e:
            print(f"获取权限摘要错误: {e}")
            return {}
